//TODO: dilate: Test

using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// Dilate is an algorithm to dilate a binary image using a 3x3 kernel.
    /// </summary>
    public class Dilate : BaseForeBackgroundColorFilter
    {
        private int m_nIterations = 1;
        private int[] m_aKernel = new int[] { 1, 1, 1, 1, 1, 1, 1, 1, 1 };

        /// <summary>
        /// Default no-arg constructor.        
        /// </summary>        
        public Dilate()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Dilate"/> class.
        /// </summary>
        /// <param name="_dilate">The _dilate.</param>
        internal Dilate(Dilate _dilate)
        {
            this.m_aKernel = _dilate.m_aKernel;
            this.m_nIterations = _dilate.m_nIterations;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Dilate"/> class.
        /// </summary>
        /// <param name="_aKernel">The _a kernel.</param>
        /// <param name="_nIterations">The _n iterations.</param>
        public Dilate(int[] _aKernel, int _nIterations)
        {
            this.m_aKernel = _aKernel;
            this.m_nIterations = _nIterations;
        }

        /// <summary>
        /// Gets or sets the kernel.
        /// </summary>
        /// <value>The kernel.</value>
        public int[] Kernel
        {
            get { return m_aKernel; }
            set { m_aKernel = value; }
        }

        /// <summary>
        /// Gets or sets the iterations.
        /// </summary>
        /// <value>The iterations.</value>
        public int Iterations
        {
            get { return m_nIterations; }
            set { m_nIterations = value; }
        }

        /// <summary>
        /// Execute this Filter
        /// A Debug Statement is written if a concrete Filter is called
        /// </summary>
        /// <param name="_bitmap"></param>
        /// <returns></returns>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            UnsafeBitmap bitmap = _bitmap;
            bitmap.InitializeEdgePixels();
            DilateImage(bitmap, m_aKernel, m_nIterations);
            return _bitmap;
        }

        /// <summary>
        /// Takes a point and a 2D array representing an image and a kernel, if the 
        /// area around the point matches the kernel then the method returns true.
        /// </summary>
        /// <param name="p">The point in the centre of the neighbourhood to be checked.</param>
        /// <param name="pixels">The 2D array representing the image.</param>
        /// <param name="w">The width of the image.</param>
        /// <param name="h">The height of the image.</param>
        /// <param name="kernel">The kernel used to match with the image.</param>
        /// <returns>True or false (true - the kernel and image match).</returns>
        private bool KernelMatch(Point p, UnsafeBitmap pixels,
                          int w, int h, int[] kernel)
        {
            for (int j = -1; j < 2; ++j)
            {
                for (int i = -1; i < 2; ++i)
                {
                    if (kernel[((j + 1) * 3) + (i + 1)] == 1)
                    {
                        if ((p.X + i >= 0) && (p.X + i < w) && (p.Y + j >= 0) && (p.Y + j < h))
                        {
                            if (pixels.GetPixel(p.X + i, p.Y + j) == m_ColorForeground)
                            {
                                return true;
                            }
                        }
                    }
                }
            }
            return false;
        }


        /// <summary>
        /// Returns true if the kernel consists of 9 1s.
        /// </summary>
        /// <param name="kernel">The array representing the kernel.</param>
        /// <returns>True or false (true - kernel all 1s).</returns>
        public bool KernelAll1s(int[] kernel)
        {
            for (int i = 0; i < 9; ++i)
            {
                if (kernel[i] == 0) return false;
            }
            return true;
        }

        /// <summary>
        /// Takes a BinaryFast representation of an image and a kernel
        /// and applies a single iteration of the dilate algorithm.
        /// </summary>
        /// <param name="binary">The BinaryFast representation of the input image.</param>
        /// <param name="kernel">The array representing the kernel.</param>
        /// <returns>The BinaryFast representation of the new image after dilation.</returns>        
        public UnsafeBitmap DilateSingleIteration(UnsafeBitmap binary,
                               int[] kernel)
        {
            List<Point> result = new List<Point>();
            IEnumerator it = null;
            Point p = Point.Empty;

            it = binary.m_BackgroundEdgePixels.GetEnumerator();
            if (!KernelAll1s(kernel))
            {
                while (it.MoveNext())
                {
                    p = (Point)it.Current;
                    if (KernelMatch(p, binary, binary.Width, binary.Height, kernel))
                    {

                        binary.m_ForegroundEdgePixels.Add(p);
                        result.Add(p);
                    }
                }
            }
            else
            {
                while (it.MoveNext())
                {
                    p = (Point)it.Current;
                    binary.m_ForegroundEdgePixels.Add(p);
                    result.Add(p);
                }
            }
            it = result.GetEnumerator();
            while (it.MoveNext())
            {
                binary.AddPixel((Point)it.Current);
            }
            binary.GenerateBackgroundEdgeFromForegroundEdge();
            return binary;
        }

        ///// <summary>
        ///// Takes a BinaryFast image, a kernel and the number of iterations
        ///// and performs the necessary number of dilations on the image.
        ///// </summary>
        ///// <param name="binary">The BinaryFast representation of the input image.</param>
        ///// <param name="kernel">The array representing the kernel.</param>
        ///// <param name="iterations">The requested number of iterations.</param>
        ///// <returns>The BinaryFast representation of the new image after dilation.</returns>
        /// <summary>
        /// Dilates the image.
        /// </summary>
        /// <param name="binary">The binary.</param>
        /// <param name="kernel">The kernel.</param>
        /// <param name="iterations">The iterations.</param>
        public void DilateImage(UnsafeBitmap binary, int[] kernel,
                        int iterations)
        {
            int i = 0;
            kernel[4] = 1;//Ignore centre pixel value in kernel (stops whiteout).
            while (i < iterations)
            {
                binary = DilateSingleIteration(binary, kernel);
                ++i;
            }
            binary.GenerateForegroundEdgeFromBackgroundEdge();
        }

        /// <summary>
        /// This is used to clone a filter, each filter must implement it's own clone functionality
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new Dilate(this);
        }
    }
}